// 路由 改变监听 --- 导航守卫
import React, { useEffect } from 'react';
import { Route, withRouter, useHistory, useLocation } from 'react-router-dom';

export default function GuardRouter(props) {
  const history = useHistory();
  const { pathname } = useLocation();

  const { path, component } = props;

  // 切换路由 获取 Version 版本号
  const getVersion = () => {
    fetch('/version.json')
      .then(d => d.json())
      .then(res => {
        // console.log('version 数据', res, sessionStorage.getItem('version'))
        const sessionVersion = sessionStorage.getItem('version');
        if (!res.version || !sessionVersion) return;
        if (res.version != sessionVersion) {
          const confirmVal = confirm('功能有更新刷新来获取吧！');
          // console.log('confirmVal', confirmVal)
          if (confirmVal) {
            sessionStorage.setItem('version', res.version);
          }
        }
      });
  };

  useEffect(() => {
    // console.log('开启路由监听', history, 12111)
    // 开启路由监听，实现导航守卫
    const unListen = history.listen((location, action) => {
      // console.log('location --->>>', location, action)
      getVersion();
    });
    return () => {
      unListen();
    };
  }, [pathname]);

  return (
    <Route exact path={path} component={component}>
      {props.children}
    </Route>
  );
}
